const path = require('path')
const log4js = require('koa-log4')

log4js.configure({
  // 指定输出文件类型和文件名
  appenders: {
    console: {
      type: 'console'
    },
    access: {
      type: 'dateFile',
      daysToKeep: 7, // 只保留近7天的日志
      pattern: '.yyyy-MM-dd.log', // 生成文件的规则
      filename: path.join('server/logs', 'access'), // 生成文件名
      alwaysIncludePattern: true, // 文件名始终以日期区分
      keepFileExt: true // 切割的日志保留文件扩展名，默认是false
    },
    application: {
      type: 'dateFile',
      daysToKeep: 7, // 只保留近7天的日志
      pattern: '.yyyy-MM-dd.log', // 切割文件的规则
      filename: path.join('server/logs', 'application'), // 生成文件名
      alwaysIncludePattern: true, // 文件名始终以日期区分
      keepFileExt: true // 切割的日志保留文件扩展名，默认是false
    },
  },
  categories: {
    default: { appenders: [ 'console' ], level: 'info' },
    access: { appenders: [ 'access', 'application' ], level: 'info' },
    application: { appenders: [ 'application' ], level: 'debug' }
  }
})

const logger = log4js.getLogger('application')

exports.httpLog = () => log4js.koaLogger(log4js.getLogger('access'))

exports.ctxLog = function () {
  return async (ctx, next) => {
    ctx.log = logger
    await next()
  }
}

exports.logger = logger
